import axios from 'axios'
import {getToken, setToken} from "./auth";

const request = axios.create({
    baseURL: '/api',
    timeout: 50000
})

request.interceptors.request.use(
    config => {
        // todo...
        /*debugger*/
        if (getToken()) {
            config.headers['x-token'] = getToken()
        }
        return config
    },
    error => {
        console.log(error)
        return Promise.reject(error)
    }
)

request.interceptors.response.use(
    response => {
        let token = response.headers['x-token']
        if (token) setToken(token)
        if (response.data instanceof Blob) return response
        const res = response.data
        if (res && res.code !== 200) {
            // todo...
            return Promise.reject(new Error(res.message || 'Error'))
        } else {
            return res
        }
    },
    error => {
        console.log('err' + error)
        return Promise.reject(error)
    }
)

export default request
